#include "n_epoll.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <pthread.h>
#include <stdatomic.h>
#include <errno.h>
struct poller_s {
    int        epollfd;
    int        pipe_rd;
    int        pipe_wd;
    atomic_int is_runing;   // poller是否工作
    atomic_int open_fds;    // poller中的fd
    int        max_openfds; // poller能容纳的最大文件描述符数
};
typedef struct epoll_event EpollEvent;

static int pollSetMode(EpollData* data, EpollEvent* ev)
{
    if(!data || !ev) { return 1; }
    ev->events = 0;
    if(data->mode & READEVENT) { ev->events |= EPOLLIN; }
    if(data->mode & LISTENEVENT) { ev->events |= EPOLLIN; }
    if(data->mode & WRITEEVENT) { ev->events |= EPOLLOUT; }
    if(data->mode & ETMODE) { ev->events |= EPOLLET; }
    return 0;
}

Poller_t* pollCreate(int max_openfds)
{
    Poller_t* poller = (Poller_t*)calloc(1, sizeof(Poller_t));
    if(poller) {
        poller->epollfd = epoll_create1(0);
        if(-1 == poller->epollfd) {
            printf("poller create failed:%s\n", strerror(errno));
            free(poller);
            return NULL;
        }
        poller->max_openfds = max_openfds;
        poller->is_runing   = 0;
        poller->open_fds    = 0;
    }
    return NULL;
}

int pollAdd(EpollData* data, Poller_t* poller)
{
    EpollEvent ev;
    pollSetMode(data, &ev);
    ev.data.ptr = data;
    if(epoll_ctl(poller->epollfd, EPOLL_CTL_ADD, data->fd, &ev)) {
        printf("add fd:%d to poll failed\n", data->fd);
        return 1;
    }
    return 0;
}

void* pollWait(void* arg) { }

int pollStart(Poller_t* poller)
{
    return 0;
}

int pollDel(EpollData* data, Poller_t* poller)
{
    return 0;
}

int pollChangeMode(int mode, EpollData* data, Poller_t* poller)
{
    return 0;
}

int pollDestroy(Poller_t* poller)
{
    return 0;
}